<?php

namespace style\lib;

use app\confg\web;

/**
 * Created by 豆豆.
 * User: longrbl@163.com
 * Date: 2016/9/12
 * Time: 23:17
 * 请求类 包括get post 获取url片段
 */
class request
{
  /**
   * 路由控制器 通过路由调指定控制器和方法
   * 地址必须是伪静态后的格式http://www.***.com/index/index
   */
  public $request = '';
  public $response = '';
  public $service = '';


  function __construct($request, $response, $service)
  {
    $this->request = $request;
    $this->response = $response;
    $this->service = $service;
  }

  public function run()
  {
    $url = $this->request->server['path_info'];
    $url = trim($url, '/');
    if (empty($url)) {
      $class_apth = PATH . '/controller/IndexController.php';
      if (is_file($class_apth)) {
        try {
          include_once $class_apth;
          $this->request->model = PATH;//设置项目目录
          $ctlr_class = new \app\controller\IndexController($this->request, $this->response, $this->service);
          $ctlr_class->actionIndex();
        } catch (\Exception $e) {
          throw new \Exception($e->getMessage());
        }
      }
    }
    $url_array = explode('/', $url);
    $web_confg = web::module();
    if (!empty($web_confg[$url_array[0]])) {
      $new = isset($url_array[0]) ? '\app\module\\' . $url_array[0] . '\controller\\' : '\app\module\\' . $url_array[0] . 'controller\\';
      $controller = isset($url_array[1]) ? ucfirst($url_array[1]) . 'Controller' : 'IndexController';
      $action = isset($url_array[2]) ? 'action' . ucfirst($url_array[2]) : 'actionIndex';
      $class_apth = APP . '/module/' . $url_array[0] . '/controller/' . $controller . '.php';
      if (is_file($class_apth)) {
        try {
          include_once $class_apth;
          $class_new = $new . $controller;
          $this->request->model = APP . '/module/' . $url_array[0];
          $ctlr_class = new $class_new($this->request, $this->response, $this->service);
          $ctlr_class->$action();
        } catch (\Exception $e) {
          throw new \Exception($e->getMessage());
        }
      }
    } else {
      $controller = isset($url_array[0]) ? '\app\controller\\' . ucfirst($url_array[0]) . 'Controller' : '\app\controller\IndexController';
      $action = isset($url_array[1]) ? 'action' . ucfirst($url_array[1]) : 'actionIndex';
      $class_apth = PATH . '/controller/' . ucfirst($url_array[0]) . 'Controller.php';
      if (is_file($class_apth)) {
        try {
          include_once $class_apth;
          $this->request->model = PATH;
          $ctlr_class = new $controller($this->request, $this->response, $this->service);
          $ctlr_class->$action();
        } catch (\Exception $e) {
          throw new \Exception($e->getMessage());
        }
      }
    }
  }
}